package com.sk.skplanet.commute.actions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Vector;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.sk.skplanet.commute.exceptions.BusAPIException;
import com.sk.skplanet.commute.views.RouteList;
import com.sk.skplanet.commute.vo.Data;

public class RegisteringTask extends AsyncTask<Void, String, Boolean> {
	private ProgressDialog dialog;
	private String email;
	private String password;
	private String errMsg;
	private Context context;

	public RegisteringTask(Context context, String email, String password) {
		super();
		this.email = email;
		this.password = password;
		this.context = context;
	}
	
	private JSONObject getJSON(String URL, List<NameValuePair> params) throws IOException, JSONException, BusAPIException {
		String paramString = URLEncodedUtils.format(params, Data.ENCODING);
		String url = URL + "?" + paramString;
		
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		
		InputStream is = httpclient.execute(httpget).getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, Data.ENCODING));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null)
			sb.append(line + "\n");
		is.close();
		
		JSONObject result = new JSONObject(sb.toString());
		
		if(result.getString("success").equals("ERROR"))
			throw new BusAPIException(result.getString("message"));
		
		return result;
	}
	
	@Override
	protected Boolean doInBackground(Void... params) {
		try {
			Thread.sleep(1000);
			
			Vector<NameValuePair> nameValue = new Vector<NameValuePair>();
			
			nameValue.add(new BasicNameValuePair("email", email));
			nameValue.add(new BasicNameValuePair("passwd", password));
			
			JSONObject result = getJSON(Data.URL_DEFAULT + Data.URL_REGISTER, nameValue);
			result = result.getJSONObject("data");
			String userId = result.getString("memberId");
			
			// Data.AUTH_KEY for use
			Data.AUTH_KEY = result.getString("authKey");
			// 2-2. Update authKey
//			if (savePassword) {
//				new SQLiteTask().updateAuthKey(data.getString("authKey"));
//			}
			// 3. getting user data.
			nameValue = new Vector<NameValuePair>();
			nameValue.add(new BasicNameValuePair("id", userId));
			result = getJSON(Data.URL_DEFAULT + Data.URL_GET, nameValue);
			Data.memberData = JsonParsing.parseMemberFromJsonObject(result);
			
			
		} catch (BusAPIException e) {
			errMsg = e.getMessage();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return true;
	}

	@Override
	protected void onPostExecute(Boolean success) {
		super.onPostExecute(success);
		if (dialog != null) dialog.dismiss();
		
		if(success) {
			Intent intentRouteList = new Intent(context, RouteList.class);
			context.startActivity(intentRouteList);
			if (context != null) ((Activity) context).finish();
		} else {
			Toast.makeText(context, errMsg, Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onPreExecute() {
		dialog = ProgressDialog.show(context, "", "불러오는 중입니다.", true);
	}
	
}
